# import snowboydecoder
from Python3 import snowboydecoder
import pyaudio
import wave

class SnowboyWakeup:
    def __init__(self, model_path, callback):
        self.model_path = model_path
        self.callback = callback
        self.detector = None

    def play_pcm(self,filename):
        CHUNK = 1024
        FORMAT = pyaudio.paInt16
        CHANNELS = 1
        RATE = 16000

        p = pyaudio.PyAudio()

        stream = p.open(format=FORMAT,
                        channels=CHANNELS,
                        rate=RATE,
                        output=True)

        with open(filename, 'rb') as f:
            data = f.read(CHUNK)
            while data:
                stream.write(data)
                data = f.read(CHUNK)

        stream.stop_stream()
        stream.close()
        p.terminate()

    def detected_callback(self):
        print("唤醒词检测到！")
        # 暂停所有媒体播放（这里需要根据你的具体播放器实现）
        # 例如：player.pause()

        # 播放demo1.pcm
        self.play_pcm("demo1.pcm")

        # 停止监听
        self.stop()

        # 调用外部回调
        self.callback()

    def start(self):
        # 创建检测器
        self.detector = snowboydecoder.HotwordDetector(self.model_path, sensitivity=0.5)
        print("正在监听唤醒词...")
        self.detector.start(detected_callback=self.detected_callback,
                            interrupt_check=lambda: False,
                            sleep_time=0.03)

    def stop(self):
        if self.detector:
            self.detector.terminate()
            print("唤醒词监听已停止")
